#include "Readini.h"
#include <iostream>

string ReadInI::GetConfigContents(string const &filename, string const &section, string const &key) {
    ifstream file(filename);
    if (!file.is_open()) {
        cerr << "Failed to open file: " << filename << endl;
        return "";
    }

    string line;
    bool inSection = false;
    unordered_map<string, string> sectionMap;

    while (getline(file, line)) {
        // 去除行首和行尾的空白字符
        line.erase(0, line.find_first_not_of(" \t\n\r\f\v"));
        line.erase(line.find_last_not_of(" \t\n\r\f\v") + 1);

        // 跳过空行和注释
        if (line.empty() || line[0] == ';' || line[0] == '#') {
            continue;
        }

        // 检查是否是节
        if (line[0] == '[' && line[line.size() - 1] == ']') {
            string currentSection = line.substr(1, line.size() - 2);
            if (currentSection == section) {
                inSection = true;
                sectionMap.clear();  // 清空之前的节内容
            } else {
                inSection = false;
            }
            continue;
        }

        // 如果在正确的节中，解析键值对
        if (inSection) {
            size_t equalPos = line.find('=');
            if (equalPos != string::npos) {
                string keyName = line.substr(0, equalPos);
                string value = line.substr(equalPos + 1);

                // 去除键名和值的空白字符
                keyName.erase(0, keyName.find_first_not_of(" \t\n\r\f\v"));
                keyName.erase(keyName.find_last_not_of(" \t\n\r\f\v") + 1);
                value.erase(0, value.find_first_not_of(" \t\n\r\f\v"));
                value.erase(value.find_last_not_of(" \t\n\r\f\v") + 1);

                sectionMap[keyName] = value;
            }
        }
    }

    file.close();

    // 返回指定键的值
    if (sectionMap.find(key) != sectionMap.end()) {
        return sectionMap[key];
    } else {
        cerr << "Key not found in section: " << section << endl;
        return "";
    }
}
